#include "rosyama.h"
#include "formpost.h"

#include <QDebug>
#include <QDomDocument>

#include <QFile>

#define ROSYAMA_DEBUG

RosYama::RosYama(QObject *parent) :
    QObject(parent)
{
    formPost = new FormPost(&manager);
}

void RosYama::setServer(QString xmlBase, QString htmlBase)
{
    this->xmlBase = xmlBase;
    this->htmlBase = htmlBase;
}

void RosYama::authorize(QString login, QString password)
{
    this->login = login;
    this->password = password;

    formPost->clear();

    formPost->addField("login", login);
    formPost->addField("password", password);

    loginReply = formPost->postData(xmlBase + "authorize/");
    connect(loginReply,SIGNAL(finished()),this,SLOT(loginCallback()));
}

void RosYama::loginCallback()
{
    QString errorText, warningText;

    if (loginReply->error() != QNetworkReply::NoError) {
        emit errorMessage(loginReply->errorString());
        emit loginResult(false);
        loginReply->deleteLater();
        return;
    }

    QDomDocument reply;
    reply.setContent(loginReply);

    errorText = reply.documentElement().elementsByTagName("error").item(0).toElement().text();
    warningText = reply.documentElement().elementsByTagName("warning").item(0).toElement().text();

    if (!errorText.isEmpty()) {
        emit errorMessage(errorText);
        emit loginResult(false);
        loginReply->deleteLater();
        return;
    }
    if (!warningText.isEmpty()) {
        emit errorMessage(warningText);
    }

    QDomElement userXml = reply.documentElement().elementsByTagName("user").item(0).toElement();
    QDomElement passwordHashXml = userXml.elementsByTagName("passwordhash").item(0).toElement();
    QDomElement usernameXml = userXml.elementsByTagName("username").item(0).toElement();

    fullname = usernameXml.attribute("full","");
    name = usernameXml.elementsByTagName("name").item(0).toElement().text();
    secondname = usernameXml.elementsByTagName("secondname").item(0).toElement().text();
    lastname = usernameXml.elementsByTagName("lastname").item(0).toElement().text();

    userId = userXml.attribute("id","-1").toInt();
    passwordHash = passwordHashXml.text();

    emit loginResult(true);
    loginReply->deleteLater();
}

void RosYama::geocode(QPointF coord)
{
    formPost->clear();

    formPost->addField("login", login);
    formPost->addField("passwordhash", passwordHash);
    formPost->addField("geocode",QString("%2,%1").arg(coord.x()).arg(coord.y()));

    geocodeReply = formPost->postData(xmlBase + "geocode/");
    connect(geocodeReply,SIGNAL(finished()),this,SLOT(geocodeCallback()));
}

void RosYama::geocodeCallback()
{
    QString errorText, warningText;

    if (geocodeReply->error() == QNetworkReply::NoError) {
        QDomDocument reply;
        reply.setContent(geocodeReply);

        errorText = reply.documentElement().elementsByTagName("error").item(0).toElement().text();
        warningText = reply.documentElement().elementsByTagName("warning").item(0).toElement().text();

        if (errorText.isEmpty()) {
            errorText = reply.documentElement().elementsByTagName("text").item(0).toElement().text();
        }
    } else {
        errorText = geocodeReply->errorString();
    }

    emit geocodeResult(errorText);
    geocodeReply->deleteLater();
}

void RosYama::submitHole(QString address, QPointF coord, QString comment, QString type, QVariantList photos)
{
    formPost->clear();

    formPost->addField("login",login);
    formPost->addField("passwordhash",passwordHash);
    formPost->addField("address", address);
    formPost->addField("comment", comment);
    formPost->addField("type", type);

    formPost->addField("latitude", QString("%1").arg(coord.x()));
    formPost->addField("longitude", QString("%1").arg(coord.y()));

    foreach (QVariant v, photos) {
        formPost->addFile(QString("file-%1").arg(qrand()), v.toString(), "image/jpeg");
    }

    submitHoleReply = formPost->postData(xmlBase + "add/");
    connect(submitHoleReply,SIGNAL(finished()),this,SLOT(submitHoleCallback()));
}

void RosYama::submitHoleCallback()
{
    QString errorText, warningText;

    if (submitHoleReply->error() != QNetworkReply::NoError) {
        emit submitHoleResult(false);
        emit errorMessage(submitHoleReply->errorString());
        submitHoleReply->deleteLater();
        return;
    }

    QDomDocument reply;
    reply.setContent(submitHoleReply);

    errorText = reply.documentElement().elementsByTagName("error").item(0).toElement().text();
    warningText = reply.documentElement().elementsByTagName("warning").item(0).toElement().text();

    if (!errorText.isEmpty()) {
        emit submitHoleResult(false);
        emit errorMessage(errorText);
        submitHoleReply->deleteLater();
        return;
    }
    if (!warningText.isEmpty()) {
        emit errorMessage(warningText);
    }

    emit submitHoleResult(true);
    submitHoleReply->deleteLater();
}

void RosYama::listHoles()
{
    formPost->clear();

    formPost->addField("login",login);
    formPost->addField("passwordhash",passwordHash);

    listHolesReply = formPost->postData(xmlBase + "my/");
    connect(listHolesReply,SIGNAL(finished()),this,SLOT(listHolesCallback()));
}

void RosYama::listHolesCallback()
{
    QString errorText, warningText;

    if (listHolesReply->error() != QNetworkReply::NoError) {
        emit errorMessage(listHolesReply->errorString());
        listHolesReply->deleteLater();
        return;
    }

    QDomDocument reply;
    reply.setContent(listHolesReply);

    errorText = reply.documentElement().elementsByTagName("error").item(0).toElement().text();
    warningText = reply.documentElement().elementsByTagName("warning").item(0).toElement().text();

    if (!errorText.isEmpty()) {
        emit errorMessage(errorText);
        listHolesReply->deleteLater();
        return;
    }
    if (!warningText.isEmpty()) {
        emit errorMessage(warningText);
    }

    QDomNodeList holesList = reply.documentElement().elementsByTagName("hole");
    for (unsigned int i = 0; i < holesList.length(); i++) {
        QDomNode hole = holesList.item(i);
        QString address = hole.toElement().elementsByTagName("address").item(0).toElement().text();
        QString status = hole.toElement().elementsByTagName("state").item(0).toElement().text();
        QString type = hole.toElement().elementsByTagName("type").item(0).toElement().attribute("code","unknown");
        QString date = hole.toElement().elementsByTagName("datecreated").item(0).toElement().attribute("readable", "unknown");
        QString image = htmlBase + hole.toElement().elementsByTagName("pictures").item(0).toElement()
                    .elementsByTagName("small").item(0).toElement().elementsByTagName("fresh").item(0).toElement()
                    .elementsByTagName("src").item(0).toElement().text();

        emit listHolesResult(address, status, type, date, image);
    }

    listHolesReply->deleteLater();
}

void RosYama::removeFile(QString path)
{
    if (path.startsWith("file://"))
        path.remove(0,7);
    QFile::remove(path);
}
